package com.igeek.addTwoNumbers;


/**
 * @Author: zhiyu
 * @Date:13:51
 * @DESC:
 */
public class Sum {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2,new ListNode(4,new ListNode(3)));
        ListNode l2 = new ListNode(5,new ListNode(6,new ListNode(4)));
//        ListNode l1 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))));
//        ListNode l2 = new ListNode(9, new ListNode(9));
        ListNode listNode = addTwoNumbers(l1, l2);
        System.out.println("listNode = " + listNode);
        while (listNode!=null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode(0);
        ListNode result = l3;
        //遍历两个链表，直到两个链表都为空
        while (l1 != null || l2 != null) {
            //第一种情况l1链表不为空
            if (l1 != null) {
                //l1 l2都不为空
                if (l2 != null) {
                    //l1+l2<10
                    if (l3.next == null) {
                        l3.next = new ListNode();
                    }
                    if (l3.next.val + l1.val + l2.val < 10) {
                        l3.next.val = l3.next.val + l1.val + l2.val;
                        l3 = l3.next;
                        //l1+l2>=10
                    } else {
                        l3.next.val = l3.next.val + l1.val + l2.val - 10;
                        l3 = l3.next;
                        l3.next = new ListNode(1);
                    }
                    l2 = l2.next;
                    //l1不为空 l2为空
                } else {
                    if (l3.next == null) {
                        l3.next = new ListNode(l1.val);
                    }
                    if (l3.next.val + l1.val < 10) {
                        l3.next.val = l3.next.val + l1.val;
                        l3 = l3.next;
                    } else {
                        l3.next.val = l3.next.val + l1.val - 10;
                        l3 = l3.next;
                        l3.next = new ListNode(1);
                    }

                }
                l1 = l1.next;
                //第二种情况l1链表为空
            } else {
                //l1为空  l2不为空
                if (l2 != null) {
                    if (l3.next == null) {
                        l3.next = new ListNode(l2.val);
                    } else {
                        if (l3.next.val + l2.val < 10) {
                            l3.next.val = l3.next.val + l2.val;
                            l3 = l3.next;
                        } else {
                            l3.next.val = l3.next.val + l2.val - 10;
                            l3 = l3.next;
                            l3.next = new ListNode(1);
                        }
                    }
                    l2 = l2.next;
                }
            }
        }
        return result.next;
    }
}
